import { MoveType, AnimationKey, SkillAnimationId, CampId, BattleSet } from '../define/BattleDefine';

export class tool {
  //读取json
  public static JsonGather: any = {};
  public static loadJson(key: string) {
    return new Promise((resolve, reject) => {
      cc.loader.loadRes('config/' + key, (err, json) => {
        if (err) {
          console.log(key + 'Machao日志_Json解析报错:', err);
          reject();
        } else {
          tool.JsonGather[key] = json.json;
          resolve();
        }
      });
    });
  }

  //重新设置贴图
  public static setSource(node: cc.Sprite, source: string, onDoneShow: boolean = false): void {
    if (source == '') {
      node.getComponent(cc.Sprite).spriteFrame = null;
    } else {
      cc.loader.loadRes(source, cc.SpriteFrame, function (err, spriteFrame) {
        if (err) {
          cc.error(err.message);
          return;
        }
        if (onDoneShow) node.node.active = true;
        node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
      });
    }
  }

  //重新设置贴图 并执行回调
  public static setSourceCallBack(node: cc.Sprite, source: string, call: Function, callObj: any = null): void {
    if (source == '') {
      node.getComponent(cc.Sprite).spriteFrame = null;
    } else {
      cc.loader.loadRes(source, cc.SpriteFrame, function (err, spriteFrame) {
        if (err) {
          cc.error(err.message);
          return;
        }
        node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
        if (call && callObj) {
          call.apply(callObj);
        } else if (call) {
          call();
        }
      });
    }
  }

  public static setSourceSync(node: cc.Sprite, source: string, onDoneShow: boolean = false) {
    return new Promise((resolve, reject) => {
      cc.loader.loadRes(source, cc.SpriteFrame, function (err, spriteFrame) {
        if (err) {
          reject();
          cc.error(err.message);
          return;
        }
        if (onDoneShow) node.node.active = true;
        node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
        resolve();
      });
    });
  }

  //设置节点纹理
  public static setTextureAsync(node: cc.Node, url: string) {
    if (url === null) {
      console.error('路径不能为null！');
      return;
    } else if (url === '') {
      node.getComponent(cc.Sprite).spriteFrame = null;
    } else {
      cc.loader.loadRes(url, cc.SpriteFrame, function (err, spriteFrame) {
        if (err) {
          cc.error(err.message);
          return;
        }

        node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
      });
    }
  }

  //设置文本信息
  public static setLabel(node: cc.Node, txt: any) {
    if (typeof txt === 'number') {
      txt = txt.toString();
    } else if (typeof txt === 'string') {
      txt = txt;
    } else {
      console.error('不能将非数字以及字符串的值转换为文本');
      return;
    }

    let label = node.getComponent(cc.Label);
    if (label) {
      label.string = txt;
    } else {
      console.error(`未获取到${node.name}节点的Label组件`);
    }
  }

  /**
   * 预制体对象池
   *
   */
  public static prefabPool: any = {};
  public static getPrefab(key: string, prefab: cc.Prefab): cc.Node {
    if (!this.prefabPool[key]) {
      this.prefabPool[key] = [];
    }

    let pool: cc.Node[] = this.prefabPool[key];
    let reObj: any = pool.shift();
    if (!reObj) {
      reObj = cc.instantiate(prefab);
    }
    return reObj;
    //let item: cc.Prefab = this.prefabPool[key];
    //let node = cc.instantiate(item);
    //return node;
  }

  public static pushPrefab(key: string, prefab: cc.Node): void {
    if (!this.prefabPool[key]) {
      this.prefabPool[key] = [];
    }
    let pool: cc.Node[] = this.prefabPool[key];
    if (prefab) {
      pool.push(prefab);
    }
  }

  /**
   * 适配高屏
   */
  public static highNode(node: cc.Node, add: number = 0): number {
    let top: number = 0;
    if (cc.view.getViewportRect().height > 1500) {
      let widget = node.getComponent(cc.Widget);
      top = 70 + add;
      widget.top = top;
      widget.updateAlignment();
    } else {
      let widget = node.getComponent(cc.Widget);
      top = 0 + add;
      widget.top = top;
    }

    return top;
  }

  public static format(str: string, list: any) {
    var i = 0;
    for (
      var o = str.replace(/(%d)|(%i)|(%s)|(%f)|(%o)|({\d})/g, function (e) {
          if (list.length <= i) return e;
          var r = list[i++];
          return '%d' == e || '%i' == e ? parseInt(r) : r;
        }),
        s = list.length;
      s > i;
      i++
    )
      o += '    ' + list[i];
    return o;
  }

  /**
   * 获取世界坐标
   */
  public static getWorldPos(node: cc.Node): cc.Vec3 {
    let world: cc.Vec3 = node.parent.convertToWorldSpaceAR(node.position);
    return world;
  }

  /**
   * 获取相对坐标
   * 获取node1 在 node2的 哪里
   */
  public static getRelaPos(node1: cc.Node, node2: cc.Node): cc.Vec2 {
    let world1: cc.Vec3 = node1.parent.convertToWorldSpaceAR(node1.position);
    let rela2: cc.Vec3 = node2.convertToNodeSpaceAR(world1);
    let target: cc.Vec2 = new cc.Vec2(rela2.x, rela2.y);
    return target;
  }

  /**
   * 获取相对坐标
   * 获取node1里的xx坐标 在 node2的 哪里
   */
  public static getRelaPosByParent(pos: cc.Vec3 | cc.Vec2, node1: cc.Node, node2: cc.Node): cc.Vec2 {
    let world1: cc.Vec3 | cc.Vec2 = node1.convertToWorldSpaceAR(pos);
    let rela2: cc.Vec3 | cc.Vec2 = node2.convertToNodeSpaceAR(world1);
    let target: cc.Vec2 = new cc.Vec2(rela2.x, rela2.y);
    return target;
  }

  /**
   * 数字跳动
   */
  public static jumpNum(label: cc.Label, toNum: number, nowNum?: number, jumpTime: number = 1): void {
    if (nowNum) label.string = nowNum.toString();
    if (nowNum == toNum) {
      return;
    }
    label.unscheduleAllCallbacks();
    let now: number = parseInt(label.string);
    let diff: number = toNum - now;
    let turnTime: number = 30;
    if (diff < 30) {
      turnTime = 15;
    }
    let eveyTime: number = jumpTime / turnTime;
    let jumpValue: number = Math.round(diff / turnTime);

    let count: number = 0;
    label.schedule(() => {
      count++;
      if (count >= turnTime) {
        label.string = toNum.toString();
        label.unscheduleAllCallbacks();
      } else {
        label.string = (now + count * jumpValue).toString();
      }
    }, eveyTime);
  }

  private static prefabsPool: any = {}; //所有预制体
  //整理预制体数组
  public static arrangePrefab(allPrefab: Array<cc.Prefab>) {
    for (let i = 0; i < allPrefab.length; i++) {
      if (allPrefab[i] instanceof cc.Prefab) {
        let key = allPrefab[i].name;
        tool.prefabsPool[key] = allPrefab[i];
      }
    }
  }
  //得到预制体实例
  public static getPrefabIns(key: string): cc.Node {
    let prefab: cc.Prefab = this.prefabsPool[key];
    let node = cc.instantiate(prefab);
    return node;
  }

  //动态加载预制体
  public static getPrefabDynamic(url: string, cb: Function) {
    cc.loader.loadRes(url, cc.Prefab, (err, prefab) => {
      if (err) {
        console.log('加载错误', err);
        return;
      } else {
        let node = cc.instantiate(prefab);
        cb(node);
      }
    });
  }

  /**
   * 设置招式贴图
   */
  public static setMoveIcon(sprite: cc.Sprite, moveType: MoveType): void {
    let imgName: string = 'images/battle/move_icon/';
    switch (moveType) {
      case MoveType.Quan:
        imgName += 'quan';
        break;
      case MoveType.Jian:
        imgName += 'jian';
        break;
      case MoveType.NeiGong:
        imgName += 'nei';
        break;
      case MoveType.AnQi:
        imgName += 'an';
        break;
    }
    this.setSource(sprite, imgName);
  }

  /**
   * 根据animationiD 得到 key值
   */
  public static getSkillAniKeyById(id: SkillAnimationId): AnimationKey {
    let key: AnimationKey = AnimationKey.stand;

    switch (id) {
      case SkillAnimationId.quan:
        key = AnimationKey.quan;
        break;
      case SkillAnimationId.jian:
        key = AnimationKey.jian;
        break;
      case SkillAnimationId.neigong:
        key = AnimationKey.sit;
        break;
      case SkillAnimationId.anqi:
        key = AnimationKey.anqi;
        break;
      case SkillAnimationId.zhi:
        key = AnimationKey.zhi;
        break;
      case SkillAnimationId.zhua:
        key = AnimationKey.zhi;
        break;
      case SkillAnimationId.tui:
        key = AnimationKey.zhang;
        break;
    }

    return key;
  }

  /**
   * 获取英雄位置
   */
  public static getHeroPos(camp: CampId, posIndex: number): cc.Vec2 {
    let p: cc.Vec2;
    let x: number = 0;
    switch (camp) {
      case CampId.Me:
        x = BattleSet.MidX - posIndex * BattleSet.HeroWidth - BattleSet.HeroWidth / 2;
        break;
      case CampId.Enemy:
        x = BattleSet.MidX + posIndex * BattleSet.HeroWidth + BattleSet.HeroWidth / 2;
        break;
    }
    p = new cc.Vec2(x, 0);
    return p;
  }

  //public getEftName
}
